<template>
    <div class="template-center-page">
        <div class="template-type">
            <div v-for="(item, index) in templateType" :key="index"
                :class="['type-item', item.value == currentTemp && 'active']" @click="changeTempType(item)">
                {{ $t(item.label) }}
            </div>
        </div>
        <div class="template-body">
            <div class="template-nav-box" v-resize="resize">
                <div class="template-page-per" @click="perItem()" :class="[scrollLeft == 0 && 'disabled']"
                    v-if="showArrow">
                    <svg class="icon">
                        <use xlink:href="#keowledge-xiala-shouqi"></use>
                    </svg>
                </div>
                <div class="template-nav-bg-left" :style="getCurrentStyle.left"></div>
                <div style="width:100%;overflow: hidden;position: relative;z-index:2;" id="templateNavRef"
                    ref="templateNavRef">
                    <div class="template-nav-items">
                        <div class="template-nav-item" :class="[item.id == checkedClass && 'active']"
                            v-for="(item, index) in classifList" :key="index" @click="changeClass(item, index)"
                            :id="`template-nav-item-${index}`" :title="item.typeName">
                            <svg class="type-icon" v-if="item.icon">
                                <use v-bind:xlink:href="`#${item.icon}`"></use>
                            </svg>
                            <span>{{ item.typeName }}</span>
                        </div>
                    </div>
                </div>
                <div class="template-nav-bg-right" :style="getCurrentStyle.right"></div>
                <div class="template-page-next" @click="nextItem()" :class="[isScrollEnd && 'disabled']"
                    v-if="showArrow">
                    <svg class="icon">
                        <use xlink:href="#keowledge-xiala-shouqi"></use>
                    </svg>
                </div>
            </div>
            <div class="right" v-loading="listLoading">
                <el-scrollbar v-if="templateList.length != 0">
                    <div class="temp-items">
                        <div v-for="(item, index) in templateList" :key="index" class="temp-item"
                            @click="openTemplate(item)">
                            <!-- <img class="bottom-right" src="../../assets/common/bottom-right.png"> -->
                            <div class="temp-title" v-tooltip-auto-show>
                                <filePng :type="item.type" :nameSuffix="item.nameSuffix" :id="`file-icon-${index}`"
                                    @load="imgLoadSuccess(index)"></filePng>
                                <el-tooltip :content="item.name" effect="light">
                                    <span>{{ item.name }}</span>
                                </el-tooltip>
                            </div>
                            <img class="temp-cover" :src="getFileUrl(item.coverUrl)" />
                            <div class="tmep-bg-mark" :id="`tmep-bg-mark-${index}`"></div>
                        </div>
                    </div>
                </el-scrollbar>
                <jvs-empty v-if="templateList.length == 0"></jvs-empty>
            </div>
        </div>
        <!-- <div class="template-body">
        <div class="left" v-loading="loading">
            <el-scrollbar>
                <div class="class-item" :class="[item.id==checkedClass&& 'active']" v-for="(item,index) in classifList" :key="index" v-tooltip-auto-show
                    @click="changeClass(item)">
                    <svg class="type-icon" v-if="item.icon">
                        <use v-bind:xlink:href="`#${item.icon}`"></use>
                    </svg>
                    <el-tooltip :content="item.typeName" effect="light">
                        <span>{{item.typeName}}</span>
                    </el-tooltip>
                </div>
            </el-scrollbar>
        </div>
        <div class="right" v-loading="listLoading">
            <el-scrollbar v-if="templateList.length!=0">
                <div  class="temp-items">
                    <div v-for="(item,index) in templateList" :key="index" class="temp-item" @click="openTemplate(item)">
                        <img class="bottom-right" src="../../assets/common/bottom-right.png">
                        <div class="temp-title" v-tooltip-auto-show>
                            <filePng :type="item.type" :nameSuffix="item.nameSuffix" :id="`file-icon-${index}`" @load="imgLoadSuccess(index)"></filePng>
                            <el-tooltip :content="item.name" effect="light">
                                <span>{{item.name}}</span>
                            </el-tooltip>
                        </div>
                        <img class="temp-cover" :src="getFileUrl(item.coverUrl)"/>
                        <div class="tmep-bg-mark" :id="`tmep-bg-mark-${index}`"></div>
                    </div>
                </div>
            </el-scrollbar>
            <jvs-empty v-if="templateList.length==0"></jvs-empty>
        </div>
    </div> -->
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    getCurrentInstance,
    computed,
    watchEffect,
    nextTick
} from 'vue'
import ColorThief from 'colorthief'
const colorThief = new ColorThief()
import { useRouter, useRoute } from "vue-router"
import filePng from '@/views/common/filePng.vue'
import defaultUrl from '@/assets/images/wel.png'
import { getTemplateTypeAll, pageTemplate } from '@/api/template'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();
const route = useRoute()
const emit = defineEmits([""])
const props = defineProps({})
const { proxy } = getCurrentInstance()
const templateType = ref([
    {
        label: 'message.typeMenu.staticTemplate',
        value: "text"
    }, {
        label: 'message.typeMenu.dynamicTemplate',
        value: 'variable'
    }
])
const currentTemp = ref('text')
const classifList = ref([])
const renderClassifList = ref([])
const checkedClass = ref('')
const checkedIndex = ref(-1)
const templateList = ref([])
const loading = ref(false)
const listLoading = ref(false)
const parentId = ref('')
const parentName = ref('')
const getCurrentStyle = ref({})
const navBarWidth = ref(0)
const scrollLeft = ref(0)
const templateNavRef = ref()
const scrollIndex = ref(0)
const showArrow = ref(false)
const isScrollEnd = ref(false)
const isFirstRender = ref(false)
onMounted(() => {
    parentId.value = route.query.parentId
    parentName.value = route.query.parentName
    init()
})
// 计算偏移量
watchEffect(() => {
    [navBarWidth.value, checkedIndex.value]
    if (templateNavRef.value?.scrollWidth > navBarWidth.value) {
        showArrow.value = true
    } else {
        showArrow.value = false
    }
    if (!isFirstRender.value && checkedIndex.value != -1) {
        getScrollLeft()
        isFirstRender.value = true
    }
    if (checkedIndex.value != -1) {
        const width = document.getElementById(`template-nav-item-${checkedIndex.value}`)?.clientWidth
        const offLeft = document.getElementById(`template-nav-item-${checkedIndex.value}`)?.offsetLeft + 24
        let left = offLeft + width - scrollLeft.value
        // 当当前选中的偏移量大于宽度的时候只能取宽度
        if (navBarWidth.value < left) {
            left = navBarWidth.value - 24
        }
        getCurrentStyle.value = {
            left: {
                width: `${offLeft - scrollLeft.value}px`
            },
            right: {
                left: `${left}px`,
                width: `calc(100% - ${left}px)`
            }
        }
    } else {
        getCurrentStyle.value = {}
    }
    if (isFirstRender.value && checkedIndex.value != -1) {
        getScrollLeft()
    }
})
watch(() => scrollLeft.value, () => {
    if (templateNavRef.value?.scrollWidth) {
        isScrollEnd.value = templateNavRef.value?.scrollWidth <= scrollLeft.value + navBarWidth.value
    } else {
        isScrollEnd.value = false
    }
})
function resize({ width }) {
    navBarWidth.value = width
}
function perItem() {
    if (scrollLeft.value <= 0) return
    let offLeftSum = 0
    for (; scrollIndex.value >= 0; scrollIndex.value--) {
        offLeftSum += document.getElementById(`template-nav-item-${scrollIndex.value}`)?.clientWidth
        if (offLeftSum > (navBarWidth.value - 48)) {
            scrollLeft.value = document.getElementById(`template-nav-item-${scrollIndex.value}`)?.offsetLeft
            templateNavRef.value.scrollTo({
                top: 0,
                left: scrollLeft.value,
                behavior: 'smooth'
            })
            break
        }
    }

}
function nextItem(flag) {
    if (templateNavRef.value?.scrollWidth <= scrollLeft.value + navBarWidth.value) return
    let offLeftSum = 0, offLeft = 0
    for (let i = 0; i < classifList.value.length; i++) {
        offLeft = document.getElementById(`template-nav-item-${i}`)?.clientWidth
        offLeftSum += offLeft
        if (offLeftSum - scrollLeft.value < (navBarWidth.value - 48)) {
            offLeft = 0
        } else {
            scrollIndex.value = i
            getScrollLeft()
            if (!flag) {
                templateNavRef.value.scrollTo({
                    top: 0,
                    left: scrollLeft.value,
                    behavior: 'smooth'
                })
            }
            break
        }
    }
}
function init() {
    getTemplateTypeList()
}
function getScrollLeft() {
    scrollLeft.value = document.getElementById(`template-nav-item-${scrollIndex.value}`)?.offsetLeft
    if (scrollLeft.value > templateNavRef.value.scrollWidth - templateNavRef.value.clientWidth) {
        scrollLeft.value = templateNavRef.value.scrollWidth - templateNavRef.value.clientWidth
    }
}
function getTemplateTypeList() {
    loading.value = true
    checkedIndex.value = -1
    getTemplateTypeAll({
        templateType: currentTemp.value
    }).then(res => {
        if (res.data.code == 0) {
            classifList.value = res.data.data
            classifList.value.splice(0, 0, {
                id: '',
                icon: 'keowledge-gengduomoban',
                typeName: $t('message.text.all')
            })
            if (classifList.value.length > 0) {
                checkedClass.value = classifList.value[0].id
                nextTick(() => {
                    checkedIndex.value = 0
                })
            }
            getCheckedTempList()
        }
    }).finally(() => {
        loading.value = false
    })
}
function getFileUrl(url) {
    switch (url) {
        case '/assets/images/wel.png':
        case '/styles/wel.png':
            return defaultUrl
            break
        default:
            return url
            break
    }
}
function getCheckedTempList() {
    listLoading.value = true
    pageTemplate({
        typeId: checkedClass.value,
        templateType: currentTemp.value,
        size: 1000,
        current: 1
    }).then(res => {
        if (res.data.code == 0) {
            templateList.value = res.data.data.records
        }
    }).finally(() => {
        listLoading.value = false
    })
}
function changeClass(item, index) {
    checkedClass.value = item.id
    checkedIndex.value = index
    getCheckedTempList()
}
function changeTempType(item) {
    if (item.value != currentTemp.value) {
        currentTemp.value = item.value
        isFirstRender.value = false
        getTemplateTypeList()
    }
}
function imgLoadSuccess(index) {
    let imgDom = document.getElementById(`file-icon-${index}`)
    let arr = colorThief.getColor(imgDom)
    document.getElementById(`tmep-bg-mark-${index}`).style.background = `linear-gradient(168deg,rgba(${arr.join(',')},0.1) 11%, transparent 35%)`
}
function openTemplate(item) {
    // 打开模板
    proxy.$openTemplateView({
        templateInfo: item,
        templateType: currentTemp.value,
        parentId: parentId.value,
        parentName: parentName.value
    })
}
</script>
<style lang="scss" scoped>
.template-center-page {
    position: relative;
    width: 100%;
    height: 100%;

    .template-type {
        display: flex;
        align-items: end;
        padding: 0px 24px;
        margin-bottom: 8px;
        font-size: 16px;
        color: #6f7588;

        .type-item {
            height: 30px;
            display: flex;
            align-items: flex-end;
            cursor: pointer;
            padding-bottom: 6px;
            @include SourceHanSansCN-Regular;
        }

        .type-item+.type-item {
            margin-left: 32px;
        }

        .active {
            // font-size: 20px;
            color: #363b4c;
            @include SourceHanSansCN-Bold;
            position: relative;

            &::after {
                position: absolute;
                content: '';
                width: 100%;
                height: 2px;
                background-color: #363b4c;
                bottom: 0px;
                left: 0px;
                border-radius: 2px 0px 2px 0px;
            }
        }
    }

    .template-body {
        background: url('../../assets/images/template_bg.png');
        background-size: cover;
        background-repeat: no-repeat;
        height: calc(100% - 44px);

        .template-nav-box {
            position: relative;
            overflow: hidden;
            padding-left: 24px;
            padding-right: 24px;
            box-sizing: border-box;

            .template-nav-items {
                display: inline-flex;
                height: 48px;
                // background: #FFFFFF;
                align-items: center;
                box-sizing: border-box;
                position: relative;
                z-index: 2;
                overflow: hidden;

                .template-nav-item {
                    display: flex;
                    height: 48px;
                    min-width: 60px;
                    align-items: center;
                    // background: #FFFFFF;
                    background: transparent;
                    padding: 0px 24px;
                    cursor: pointer;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;

                    // border-radius: 8px 8px 0  0;
                    span {
                        font-size: 14px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    .type-icon {
                        width: 16px;
                        min-width: 16px;
                        height: 16px;
                        margin-right: 8px;
                    }
                }

                .active {
                    // background: transparent;
                    color: #1E6FFF;
                }
            }

            .template-nav-bg-left,
            .template-nav-bg-right {
                background-color: #fff;
                z-index: 1;
                transition: all 0.3s;
            }

            .template-nav-bg-left {
                position: absolute;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                border-radius: 0 0 8px 0;

                &::after {
                    position: absolute;
                    content: '';
                    right: -8px;
                    top: 0;
                    width: 8px;
                    height: 8px;
                    background: radial-gradient(circle at 100% 100%, transparent 8px, #FFF 9px);
                }
            }

            .template-nav-bg-right {
                position: absolute;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                border-radius: 0 0 0 8px;

                &::after {
                    position: absolute;
                    content: '';
                    top: 0;
                    width: 8px;
                    height: 8px;
                    left: -8px;
                    background: radial-gradient(circle at 5% 100%, transparent 8px, #FFF 9px);
                }
            }

            .template-page-per,
            .template-page-next {
                position: absolute;
                width: 24px;
                height: 24px;
                z-index: 3;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                background-color: #F5F6F7;
                cursor: pointer;
                top: 50%;
                transform: translateY(-50%);

                .icon {
                    width: 16px;
                    height: 16px;
                }
            }

            .template-page-per {
                left: 0px;

                .icon {
                    transform: rotate(180deg);
                }
            }

            .template-page-next {
                right: 0px;
            }
        }

        .right {
            width: calc(100% - 0px);
            height: calc(100% - 48px);

            // background: #F5F6F7;
            .temp-items {
                padding: 24px;
                display: flex;
                flex-wrap: wrap;
                grid-column-gap: 16px;
                grid-row-gap: 16px;

                .temp-item {
                    width: 216px;
                    height: 212px;
                    border-radius: 6px;
                    position: relative;
                    overflow: hidden;
                    background-color: #fff;
                    // background-image: url('../../assets/common/template-bg.png');
                    // background-size: 100% 100%;
                    // background-repeat: no-repeat;
                    cursor: pointer;
                    padding: 12px;
                    box-sizing: border-box;
                    border: 1px solid #EEEFF0;
                    z-index: 1;

                    .tmep-bg-mark {
                        position: absolute;
                        left: 0px;
                        top: 0px;
                        width: 100%;
                        height: 100%;
                        z-index: 0;
                    }

                    .bottom-right {
                        position: absolute;
                        right: -6px;
                        bottom: -2px;
                        z-index: 2;
                        width: 75px;
                        z-index: 3;
                    }

                    .temp-title {
                        font-size: 14px;
                        color: #363B4C;
                        display: flex;
                        @include SourceHanSansCN-Regular;
                        align-items: center;
                        position: relative;
                        z-index: 1;

                        span {
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                        }

                        img {
                            width: 16px;
                            height: 16px;
                            margin-right: 8px;
                        }
                    }

                    .temp-cover {
                        position: relative;
                        z-index: 1;
                        width: 192px;
                        height: 160px;
                        margin-top: 10px;
                    }
                }
            }
        }
    }
}
</style>